<template>
  <div class="app-container">
    <div class="filter-container" style="display: flex;align-items: center;justify-content: space-between;">
      <el-button @click="handleCreate" v-waves size="mini" type="success">
        新增收款账号
      </el-button>
    </div>
    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row
      style="width: 100%;">
      <el-table-column label="账号" prop="account" align="center" />
      <el-table-column label="开户人" prop="name" align="center" />
      <el-table-column label="开户行" prop="path" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" @click="handleUpdate(row)" size="mini">
            编辑
          </el-button>
          <el-popconfirm @onConfirm="handleDelete($index)" style="margin-left: 10px;" title="是否要删除该记录">
            <el-button  v-if="row.status!='deleted'" slot="reference" size="mini"
              type="danger">
              删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" label="请输入姓名" />
        </el-form-item>
        <el-form-item label="开户行地区">
          <v-distpicker :province="temp.province" :city="temp.city" :area="temp.area" @city="handleEvent($event,'city')"
            @area="handleEvent($event,'area')" @province="handleEvent($event,'province')"></v-distpicker>
        </el-form-item>
        <el-form-item label="开户行" prop="bank">
          <el-select v-model="temp.bank" placeholder="选择开户行" clearable filterable>
            <el-option v-for="item in banks" :key="item.text" :label="item.text" :value="item.text">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="temp.account" label="请输入账号" />
        </el-form-item>
        <el-form-item label="所在地址" prop="path">
          <el-input v-model="temp.path" label="请输入所在地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import waves from '@/directive/waves' // waves directive
  import VDistpicker from 'v-distpicker'
  import {
    fetchPayments,
    updatePayment,
    createPayment,
    deletePayment
  } from '@/api/pay'
  import { getBank } from '@/utils/bank';
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination

  const statusOptions = {
    0: '审核中',
    1: '已提现',
    2: '提现失败'
  }

  export default {
    components: {
      Pagination,
      VDistpicker
    },
    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        return statusOptions[status]
      }

    },
    data() {
      return {
        detail: {
          no_settle: 30
        },
        tableKey: 0,
        list: null,
        total: 0,
        banks: [],
        dialogStatus: '',
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
        },
        textMap: {
          update: '修改',
          create: '新增'
        },
        statusOptions,
        temp: {
          account: '',
          name: '',
          province: '',
          city: '',
          area: '',
          path: '',
          bank: '',
        },
        dialogFormVisible: false,
        rules: {
          account: [{
            required: true,
            message: '账户不能为空',
            trigger: 'blur'
          }],
          name: [{
            required: true,
            message: '姓名不能为空',
            trigger: 'blur'
          }],
          path: [{
            required: true,
            message: '地址不能为空',
            trigger: 'blur'
          }],
          bank: [{
            required: true,
            message: '开户行不能为空',
            trigger: 'change'
          }]
        }
      }
    },
    created() {
      this.getList()
      this.banks = getBank()
    },
    methods: {
      handleEvent(event, key) {
        this.temp[key] = event.value
      },
      getList() {
        this.listLoading = true
        fetchPayments().then(res => {
          this.list = res.data.items
          this.total = res.data.total
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },

      resetTemp() {
        this.temp = {
          account: '',
          name: '',
          province: '',
          city: '',
          area: '',
          path: '',
          bank: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogFormVisible = true
        this.dialogStatus = 'create'
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.temp.province == '' || this.temp.city == '' || this.temp.area == '') {
              return this.$message({
                message: '省市区不能为空',
                type: 'error',
              });
            }
            const tempData = Object.assign({}, this.temp)
            updatePayment(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(index) {
        deletePayment().then(() => {
          this.list.splice(index, 1)
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000
          })
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogFormVisible = true
        this.dialogStatus = 'update'
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.temp.province == '' || this.temp.city == '' || this.temp.area == '') {
              return this.$message({
                message: '省市区不能为空',
                type: 'error',
              });
            }
            createPayment(this.temp).then((res) => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      }
    }
  }

</script>